package com.tools.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.sql.Blob;
import java.util.Base64;

/**
 * @author: LU
 * @description: 图片水印工具类
 */
public class WatermarkUtils {

    //  字体颜色
    private static final Color color = new Color(255, 102, 51);
    //  字体样式
    private static final Font font = new Font("宋体", Font.PLAIN, 18);
    //  水印透明度
    private static final Float alpha = 0.8F;
    //  水印文字偏移角度
    private static final Integer degree = 45;
    //  水印文字x轴间隔宽度
    private static final Integer xStep = 80;
    //  水印文字y轴间隔高度
    private static final Integer yStep = 80;

    /**
     * 文字水印
     * @param text 文字内容
     * @param sourceImageFile 源文件
     * @param destImageFile 目标文件
     */
    public static void addTextWatermark(String text, File sourceImageFile, File destImageFile) {
        try {
            BufferedImage sourceImage = ImageIO.read(sourceImageFile);
            Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();

            AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
            g2d.setComposite(alphaChannel);
            //  设置水印属性
            g2d.setColor(color);
            g2d.setFont(font);
            //  绘制水印
            g2d.drawString(text, xStep, yStep);
            //  保存新的图片
            ImageIO.write(sourceImage, "png", destImageFile);
            g2d.dispose();

            System.out.println("Text watermark added successfully.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 图片水印
     * @param watermarkImageFile 水印图
     * @param sourceImageFile 源文件
     * @param destImageFile 目标文件
     */
    public static void addImageWatermark(File watermarkImageFile, File sourceImageFile, File destImageFile) {
        try {
            BufferedImage sourceImage = ImageIO.read(sourceImageFile);
            BufferedImage watermarkImage = ImageIO.read(watermarkImageFile);

            Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
            AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
            g2d.setComposite(alphaChannel);
            //  绘制水印
            g2d.drawImage(watermarkImage, xStep, yStep, null);
            //  保存新的图片
            ImageIO.write(sourceImage, "png", destImageFile);
            g2d.dispose();

            System.out.println("Image watermark added successfully.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 不倾斜文字平铺文字水印
     * @param text 文字内容
     * @param sourceImageFile 源文件
     * @param destImageFile 目标文件
     */
    public static void addTiledTextWatermark(String text, File sourceImageFile, File destImageFile) {
        try {
            BufferedImage sourceImage = ImageIO.read(sourceImageFile);
            Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();

            AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
            g2d.setComposite(alphaChannel);
            //  设置水印属性
            g2d.setColor(color);
            g2d.setFont(font);

            FontMetrics fontMetrics = g2d.getFontMetrics();
            int textWidth = fontMetrics.stringWidth(text);
            int textHeight = fontMetrics.getHeight();

            for (int x = 0; x < sourceImage.getWidth(); x += textWidth + xStep) {
                for (int y = textHeight; y < sourceImage.getHeight(); y += textHeight + yStep) {
                    //  绘制水印
                    g2d.drawString(text, x, y);
                }
            }
            //  保存新的图片
            ImageIO.write(sourceImage, "png", destImageFile);
            g2d.dispose();

            System.out.println("Tiled text watermark added successfully.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 倾斜全图片文字平铺文字水印（扩大水印位置否则水印图4个脚会缺失水印文字，水印后需裁剪取得原文件大小）
     * @param text 文字内容
     * @param sourceImageFile 源文件
     * @param destImageFile 目标文件
     */
    public static void addTiledAllTextWatermark(String text, File sourceImageFile, File destImageFile) {
        try {
            BufferedImage sourceImage = ImageIO.read(sourceImageFile);
            //  图片宽度
            int width = sourceImage.getWidth();
            //  图片高度
            int height = sourceImage.getHeight();

            BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = newImage.createGraphics();
            g2d.drawImage(sourceImage, 0, 0, width, height, null);

            AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
            g2d.setComposite(alphaChannel);
            //  设置水印属性
            g2d.setColor(color);
            g2d.setFont(font);
            //  设置对线段的锯齿状边缘处理
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.rotate(Math.toRadians(degree), width, (double) height / 2); // 旋转角度

            FontMetrics fontMetrics = g2d.getFontMetrics();
            //  水印文字宽度
            int textWidth = fontMetrics.stringWidth(text);
            //  水印文字高度
            int textHeight = fontMetrics.getHeight();
            //  水印宽度写入增加5倍，防止文字缺失
            int newWidth = width * 5;
            //  水印高度写入增加5倍，防止文字缺失
            int newHeight = height * 5;
            for (int x = 0; x < newWidth ; x += textWidth + xStep) {
                for (int y = textHeight; y < newHeight ; y += textHeight + yStep) {
                    //  绘制水印
                    g2d.drawString(text, x, y);
                }
            }
            //  转换成base64输出
//            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//            ImageIO.write(newImage, "png", byteArrayOutputStream);
//            byte[] bytes = Base64.getEncoder().encode(byteArrayOutputStream.toByteArray());
//            String base64 = new String(bytes);
//            base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
//            byteArrayOutputStream.close();
//            System.out.println("data:image/png;base64," + base64);

            //  保存新的图片
            ImageIO.write(newImage, "png", destImageFile);
            g2d.dispose();

            System.out.println("Tiled text watermark added successfully.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 图片平铺水印
     * @param watermarkImageFile 水印图
     * @param sourceImageFile 源文件
     * @param destImageFile 目标文件
     */
    public static void addTiledImageWatermark(File watermarkImageFile, File sourceImageFile, File destImageFile) {
        try {
            BufferedImage sourceImage = ImageIO.read(sourceImageFile);
            BufferedImage watermarkImage = ImageIO.read(watermarkImageFile);

            Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
            AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
            g2d.setComposite(alphaChannel);

            for (int x = 0; x < sourceImage.getWidth(); x += watermarkImage.getWidth() + xStep) {
                for (int y = 0; y < sourceImage.getHeight(); y += watermarkImage.getHeight() + yStep) {
                    //  绘制水印
                    g2d.drawImage(watermarkImage, x, y, null);
                }
            }
            //  保存新的图片
            ImageIO.write(sourceImage, "png", destImageFile);
            g2d.dispose();

            System.out.println("Tiled image watermark added successfully.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String text = "优友.互联";
        File sourceImageFile = new File("C:\\Users\\Re\\Desktop\\default_head.png");
        File destImageFile = new File("C:\\Users\\Re\\Desktop\\2.png");
//        addTextWatermark(text, sourceImageFile, destImageFile);
//        addTiledTextWatermark(text, sourceImageFile, destImageFile);
        addTiledAllTextWatermark(text, sourceImageFile, destImageFile);
    }
}

